package com.kaifamiao.multiton;

/**
 * 手写多例 (饿汉式实现)
 * 1、将所有构造都私有化 (避免在类外创建其实例)
 * 2、提供用于缓存本类"有限个"实例的类变量
 * 3、可以提供用于获取指定实例的类方法
 */
public class Season {

    // 定义用来缓存本类实例的类变量
    public static final Season SPRING = new Season( "春季" , "春暖花开" );
    public static final Season SUMMER;
    public static final Season AUTUMN;
    // 为类变量赋值属于对类变量的初始化，这部分代码也属于 "<clinit>"
    public static final Season WINTER = new Season( "冬季" , "白雪皑皑" );

    // 在语言规范中被称作 类初始化器 ，国内俗称 静态代码块 ( 对应 "<clinit>" )
    static {
        SUMMER = new Season( "夏季" , "夏日炎炎" );
        AUTUMN = new Season( "秋季" , "秋高气爽" );
    }

    private String name;
    private String desc;

    private Season(){
        super();
    }

    private Season(String name, String desc) {
        this.name = name;
        this.desc = desc;
    }

    public static Season getInstance( int ordinal ){
        switch ( ordinal ) {
            case 0: return SPRING;
            case 1: return SUMMER;
            case 2: return AUTUMN;
            case 3: return WINTER;
            default:
                throw new IllegalArgumentException( "不是合理的季节序数" );
        }
    }

    public static Season getInstance( String constantName ){
        if( constantName == null ) {
            throw new NullPointerException( "季节常量名称不能为空" );
        }
        String cn = constantName.toUpperCase();
        // 从 Java 7 开始允许在 switch 中使用 String类型
        switch ( cn ) {
            case "SPRING": return SPRING;
            case "SUMMER": return SUMMER;
            case "AUTUMN": return AUTUMN;
            case "WINTER": return WINTER;
            default:
                throw new IllegalArgumentException( "季节常量名称不能存在" );
        }
    }

}
